package 多线程;
/*
  实现  先生产，再消费  协同工作
  
  wait(可选毫秒) 进程进入等待，释放cpu时间片，并释放对象监视器的所有权(对象锁)，等待其他线程通过用notify唤醒
  sleep()  进程进入休眠状态，释放cpu时间片，不会释放对象监视器的所有权,

*/

public class X06生产者和消费者多线程处理
{
	public static void main(String[] args){
		Food food=new Food();
		Producter p=new Producter(food);
		Customer c=new Customer(food);
		
		Thread t1=new Thread(p);
		Thread t2=new Thread(c);
		t1.start();
		t2.start();
		
		
	}
}

class Food{
	private String name;
	private String desc;
	private boolean falg=true;//true时可生产，false可消费
	
	//消费
	public synchronized void get(){
		//不能消费时
		if(falg){
			try
			{
				this.wait();//当前线程进入等待状态
			}
			catch (InterruptedException e)
			{}
		}
		try
		{
			Thread.sleep(500);
		}
		catch (InterruptedException e)
		{}
		System.out.println(this.name + "->" + this.desc);
		falg=true;
		this.notify();//唤醒等待的线程(随机一个) notifyAll唤醒所有
	}
	//生产
	public synchronized void set(String name,String desc){
		//不能生产时
		if(!falg){
			try
			{
				this.wait();
			}
			catch (InterruptedException e)
			{}
		}
		this.name=name;
		try
		{
			Thread.sleep(500);
		}
		catch (InterruptedException e)
		{}
		this.desc = desc;
		falg=false;
		this.notify();
	}
}
//生产者
class Producter implements Runnable
{
	private Food food;

	public Producter(Food food)
	{
		this.food = food;
	}
	
	@Override
	public void run()
	{
		for(int i=0;i<20;i++){
			if(i%2==0){
				food.set("红烧肉","肥而不腻");
			}else{
				food.set("糖醋排骨","酸甜美味");
			}
		}
	}
}
//消费者
class Customer implements Runnable
{
	private Food food;

	public Customer(Food food)
	{
		this.food = food;
	}
	@Override
	public void run()
	{
		for(int i=0;i<20;i++){
			food.get();
		}
	}
}
